//
//  ViewController.m
//  self
//
//  Created by 杨泓晔 on 16/4/7.
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYViewController.h"
#import "YHYAddressCollectionViewCell.h"
#import "Masonry.h"
#import "YHYHeadCollectionReusableView.h"
#import "YHYRightView.h"
#import "StickyHeaderLayout.h"
#import "YHYPositioningCollectionReusableView.h"
#import "YHYFindSearchViewController.h"
#import <MapKit/MapKit.h>
#define HeadHeight 40
#define ItemHeight 30
#define EadgeHeight 15

@interface YHYViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,YHYRightViewDelegate>
{
    UILabel                 * _flotageLabel;//中间显示的背景框
    CLPlacemark *firstPlacemark;
    NSString *oreillyAdress;

}
@property (retain, nonatomic)UICollectionView *collection;
@property (nonatomic,retain)NSMutableArray *dataSource;
@property (nonatomic,retain)NSMutableArray *indexSource;
@property(nonatomic,retain)UIView *myheaderView;
@property(nonatomic,retain)WSCustomButton *goBack;
@property (nonatomic,retain)UILabel *titlename;
@property(nonatomic,assign) CLLocationCoordinate2D  coordinate;


@end

@implementation YHYViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    self.dataSource = [[NSMutableArray alloc] init];
    self.indexSource = [[NSMutableArray alloc] init];
    
    [self getData];

    [self creatView];
    
    
    //导航栏
    self.myheaderView = [[UIView alloc]init];
    self.myheaderView.backgroundColor = HEADVC;
    self.myheaderView.userInteractionEnabled = YES;
    [self.view addSubview:self.myheaderView];
    [self.myheaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.left.top.mas_equalTo(@0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 129.00*AUTO_WIDTH/2));
        
    }];
    
    
   
    
    
    //返回 左边按钮
    self.goBack = [[WSCustomButton alloc]init];
    [self.goBack setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [self.goBack addTarget:self action:@selector(Back:) forControlEvents:UIControlEventTouchUpInside];
    [self.myheaderView addSubview:self.goBack];
    [_goBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.myheaderView).offset(51.00*AUTO_WIDTH/2);     //  相对于self.view 顶部 10
        make.left.equalTo(self.myheaderView).offset(20.00*AUTO_WIDTH/2);    //  相对于self.view 左边 10
        make.size.mas_equalTo(CGSizeMake(30.00*AUTO_WIDTH, 30.00*AUTO_WIDTH));
        
    }];
    
    
    
    
    
//    
//    //标题
//    self.titlename.text = @"淘宝平面模特";
//    self.titlename.backgroundColor = CFBridgingRelease(HH);
//   // self.titlename.font = TEXTTITLEFONT;
//    self.titlename.textColor = HS;
//    self.titlename.adjustsFontSizeToFitWidth = YES;
//    self.titlename.textAlignment =  NSTextAlignmentCenter;
//    [self.myheaderView addSubview:self.titlename];
//    self.titlename.userInteractionEnabled = YES;
//    [self.titlename mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.myheaderView).offset(66.00*AUTO_WIDTH/2);
//        make.centerXWithinMargins.mas_equalTo(self.myheaderView);
//        make.height.mas_equalTo(20 * AUTO_WIDTH);
//        
//    }];
//    

    

    
    
}

- (void)Back:(UIButton *)bck{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)creatView{
    StickyHeaderLayout *layout = [[StickyHeaderLayout alloc] init];
    _collection = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [self.view addSubview:_collection];
    [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(149/2);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(self.view.frame.size.width - 30);
        make.height.mas_equalTo(self.view);
        
    }];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.alwaysBounceVertical = YES;
    _collection.showsVerticalScrollIndicator = NO;
    [_collection setIsAccessibilityElement:YES];
   // [_collection setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
    [_collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
   
    layout.itemSize = CGSizeMake((self.view.frame.size.width-90)/3, ItemHeight);
    layout.sectionInset = UIEdgeInsetsMake(EadgeHeight, 15, EadgeHeight, 15);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    self.view.backgroundColor = LV;
    _collection.backgroundColor = LV;
    
    [_collection registerClass:[YHYHeadCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYHeadCollectionReusableView"];
    [_collection registerClass:[YHYPositioningCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYPositioningCollectionReusableView"];
    [_collection registerClass:[YHYAddressCollectionViewCell class] forCellWithReuseIdentifier:@"YHYAddressCollectionViewCell"];
    
    
    
    YHYRightView *right = [[YHYRightView alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 24, 120, 20, 500)];
    [self.view addSubview:right];
    right.myDelegate = self;
    right.backgroundColor = LV;
    
    
    //中间圈圈
    _flotageLabel = [UILabel new];
   
    _flotageLabel.backgroundColor =[UIColor whiteColor];
    //modify by wsf start-----
//    _flotageLabel.hidden = NO;
    _flotageLabel.alpha = 0;
    //modify by wsf end-----
    [_flotageLabel.layer  setCornerRadius:24];
    _flotageLabel.layer.masksToBounds = YES;
    _flotageLabel.textAlignment = NSTextAlignmentCenter;
    _flotageLabel.textColor = [UIColor whiteColor];
   [self.view addSubview:_flotageLabel];
    [_flotageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo((self.view.bounds.size.width - 50)/2);
        make.top.mas_equalTo((self.view.bounds.size.height - 50)/2);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
        
    }];
  
    [_collection reloadData];

}


- (void)presentindexPath:(NSIndexPath *)indexPath{
 CGFloat seactionHeaiht = indexPath.row * HeadHeight;
      //  NSInteger bigH  = HeadHeight * 2 + 15 * 4 + ItemHeight * 2;
    NSInteger bigH = HeadHeight * 2 + EadgeHeight * 4 + ItemHeight * 6 ;
    for (int i = 0; i < indexPath.row ; i++) {
//        NSLog(@"%ld",[self.dataSource[indexPath.row] count]);
        NSInteger number = (NSInteger)[self.dataSource[i] count];
       NSInteger rowHei  = (NSInteger)(number / 3) * ItemHeight ;//整行高
       
        if (number % 3 != 0) {
              bigH = bigH + HeadHeight + EadgeHeight + rowHei + EadgeHeight + (NSInteger)(number / 3) * 10 + ItemHeight;
        }
        else{
            bigH=  bigH + HeadHeight + EadgeHeight + rowHei + EadgeHeight + (NSInteger)(number / 3) * 10 - 10;
        }
       

       
    }
    
    NSLog(@"%ld",(long)bigH);
    _collection.contentOffset = CGPointMake(0, bigH);
     _flotageLabel.text = self.indexSource[indexPath.row];
    
    ////modify by wsf start-----
    
    [UIView animateWithDuration:0.4 animations:^{
        _flotageLabel.alpha = 1;
        
    } completion:^(BOOL finished) {
//       _flotageLabel.hidden = YES;
      //此处0.2秒可自己微调
        [UIView animateWithDuration:0.2 animations:^{
            _flotageLabel.alpha = 0;
        }];
            }];
    //modify by wsf end-----
    

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    NSLog(@"sadasd");
}




//-(void)collectionViewIndexTouchesBegan:(DSCollectionViewIndex *)collectionViewIndex{
//    
//    _flotageLabel.alpha = 1;
//    _flotageLabel.hidden = NO;
//}
//
//-(void)collectionViewIndexTouchesEnd:(DSCollectionViewIndex *)collectionViewIndex{
//    
//    void (^animation)() = ^{
//        _flotageLabel.alpha = 0;
//    };
//    
//    [UIView animateWithDuration:0.4 animations:animation completion:^(BOOL finished) {
//        _flotageLabel.hidden = YES;
//    }];
//}
//



//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [super touchesBegan:touches withEvent:event];
//    NSLog(@"cfsafs");
//}



- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UICollectionReusableView *reusable = nil;
        if (kind == UICollectionElementKindSectionHeader) {
            YHYPositioningCollectionReusableView *po = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYPositioningCollectionReusableView" forIndexPath:indexPath];
            po.addressL.text = @"定位";
            reusable = po;
        }
        return reusable;
    }
    if (indexPath.section == 1) {
        UICollectionReusableView *re = nil;
        if (kind == UICollectionElementKindSectionHeader) {
            YHYPositioningCollectionReusableView *po = [collectionView  dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYPositioningCollectionReusableView" forIndexPath:indexPath];
            po.addressL.text = @"热门";
            re = po;
        }
        return re;
    }
    else{
    
     UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        YHYHeadCollectionReusableView *firstV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYHeadCollectionReusableView" forIndexPath:indexPath];
        firstV.addressL.text = [self.indexSource objectAtIndex:indexPath.section - 2];
        reusableview = firstV;
           }
    
    return reusableview;
        
    }

}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==1 || indexPath.section == 0) {
        NSString *sstr = @"sdf";
        [self.deleagte presentaddName:sstr indexPath:indexPath];
        [self dismissViewControllerAnimated:YES completion:^{
            YHYFindSearchViewController *find = [YHYFindSearchViewController new];
            find.indeP = indexPath;
            find.addSte = sstr;
            
            
            
        }];

        
    }
    else{
    
    NSString *str = [[self.dataSource[indexPath.section - 2]objectAtIndex:indexPath.row ]objectForKey:@"name"];
    [self.deleagte presentaddName:str indexPath:indexPath];
    [self dismissViewControllerAnimated:YES completion:^{
        YHYFindSearchViewController *find = [YHYFindSearchViewController new];
        find.indeP = indexPath;
        find.addSte = str;
        
        
        
    }];
        
        
    }
    
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
    CGSize size = {200,HeadHeight};//20
    return size;
    //   }
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
        static NSString *ce = @"YHYAddressCollectionViewCell";
        YHYAddressCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ce forIndexPath:indexPath];
        
        //定义目的地的名称
        oreillyAdress=@"杭州";
        NSLog(@"%@",oreillyAdress);
        
        cell.addressL.text=oreillyAdress;
        NSLog(@"%@",cell.addressL.text);
        
        CLGeocoder *myGeocoder=[[CLGeocoder alloc]init];
        [myGeocoder geocodeAddressString:oreillyAdress completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
           
            if ([placemarks count] >0 && error == nil) {
                NSLog(@"Found %lu placemark(s).",(unsigned long)[placemarks count]);
                firstPlacemark=[placemarks objectAtIndex:0];
                NSLog(@"Longitud= %f",firstPlacemark.location.coordinate.longitude);
                NSLog(@"Latitude= %f",firstPlacemark.location.coordinate.latitude);
            }
            else if ([placemarks count]==0 &&error==nil){
                
                NSLog(@"Found no placemark.");
            }else if (error != nil){
                
                NSLog(@"An error occurred =%@",error);
            }
            
            //城市名称的经纬度
            self.coordinate=CLLocationCoordinate2DMake(firstPlacemark.location.coordinate.latitude,firstPlacemark.location.coordinate.longitude);
        
        }];
        
        return cell;
    }
    else{
    static NSString *ce = @"YHYAddressCollectionViewCell";
    YHYAddressCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ce forIndexPath:indexPath];
    cell.addressL.text = [[self.dataSource[indexPath.section  -  2] objectAtIndex:indexPath.row] objectForKey:@"name"];
    return cell;
    }
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{
    
    return self.dataSource.count + 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 12;
    }
    else{
    return [self.dataSource[section - 2] count];
        
    }
}




- (void)getData{
    
    NSString *plistPath = [[NSBundle mainBundle]pathForResource:@"citySort.plist" ofType:nil];
    NSArray *array = [[NSArray alloc]initWithContentsOfFile:plistPath];
    self.dataSource = [self sortArray:[NSMutableArray arrayWithArray:array]];
    
}
//排序并按首字母分组
-(NSMutableArray *)sortArray:(NSMutableArray *)arrayToSort {
    NSMutableArray *arrayForArrays = [[NSMutableArray alloc] init];
    
    //根据拼音对数组排序
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinyin" ascending:YES]];
    //排序
    [arrayToSort sortUsingDescriptors:sortDescriptors];
    
    NSMutableArray *tempArray = nil;
    BOOL flag = NO;
    
    //分组
    for (int i = 0; i < arrayToSort.count; i++) {
        NSString *pinyin = [arrayToSort[i] objectForKey:@"pinyin"];
        NSString *firstChar = [pinyin substringToIndex:1];
        if (![_indexSource containsObject:[firstChar uppercaseString]]) {
            [_indexSource addObject:[firstChar uppercaseString]];
            tempArray = [[NSMutableArray alloc] init];
            flag = NO;
        }
        if ([_indexSource containsObject:[firstChar uppercaseString]]) {
            [tempArray addObject:arrayToSort[i]];
            if (flag == NO) {
                [arrayForArrays addObject:tempArray];
                flag = YES;
            }
        }
    }
    
    return arrayForArrays;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
